<template>
  <!-- 添加或修改发票管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="基本信息" name="first">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerId">
                <el-select v-model="form.customerId" placeholder="请选择客户" filterable @change="selectCustomer" clearable
                           style="width: 300px" disabled>
                  <el-option v-for="dict in dict.type.goods_customer" ref="myselectCustomer"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
                <span v-if="taxNo">税号:{{taxNo}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销售金额" prop="amountReal">
                <el-input-number :precision="2" v-model="form.amountReal" disabled placeholder="请输入销售金额"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="乙方" prop="invoiceCompany">
                <el-select v-model="form.invoiceCompany" placeholder="请选择乙方" filterable clearable disabled
                           style="width: 300px">
                  <el-option v-for="dict in dict.type.company"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发票编号" prop="invoiceCompany">
                <el-input v-model="form.no" placeholder="请输入发票编号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开票日期" prop="invoiceDate">
                <el-date-picker clearable disabled
                                v-model="form.invoiceDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择开票日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件" prop="files">
                <file-upload :limit="1" v-model="form.files" disabled/>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="是否回款" prop="fundCallback">
                <el-select v-model="form.fundCallback" placeholder="请选择是否回款" clearable style="width: 50%;">
                  <el-option v-for="dict in dict.type.fund_callback"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="回款日期" prop="backDate">
                <el-date-picker clearable disabled
                                v-model="form.backDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择回款日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="核销总金额" prop="pinMoney">
                <el-input-number :precision="2" v-model="form.pinMoney" disabled placeholder="请输入核销总金额"/>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="剩余核销金额" prop="pinRemain">
                <el-input-number :precision="2" v-model="form.pinRemain" disabled placeholder="请输入剩余核销金额"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" v-if="showEditBtn">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
    import {addAction, getAction, getById, updateAction} from '@/api/manage'
    import {updateInvoice} from '@/api/develop/goodsInvoiceBatch'

    export default {
        name: "GoodsInvoiceForCW",
        dicts: ['goods_supplier', 'goods_customer', 'fund_callback', 'yes_no', 'company'],
        data() {
            return {
                // 遮罩层
                loading: true,
                activeName: "first",
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 表单参数
                form: {},
                columns: [],
                dataList: [],
                // 表单校验
                rules: {
                    customerId: [
                        {required: true, message: "客户名称不能为空", trigger: "blur"}
                    ],
                },
                total: 0,
                url: {
                    list: '/goodsInvoiceDetail/goodsInvoiceDetail/list',
                    listBatch: '/goodsSale/goodsSale/listBatchSale/',
                    getById: '/goodsInvoice/goodsInvoice/',
                    add: '/goodsInvoice/goodsInvoice/add',
                    edit: '/goodsInvoice/goodsInvoice/edit',
                },
                queryParams: {
                    id: null,
                    no: null,
                    amount: null,
                    amountReal: null,
                    remaining: null,
                    customerId: null,
                    customerName: null,
                    taxNo: null,
                    invoiceDate: new Date(),
                    invoiceCompany: null,
                    fundCallback: null,
                    backDate: null,
                    drawerId: null,
                    drawerName: null,
                    saleId: null,
                    saleName: null,
                    files: null,
                    status: "0",
                    delFlag: null,
                    createBy: null,
                    createTime: null,
                    updateBy: null,
                    updateTime: null,
                    remark: null
                },
                showEditBtn: true,
                taxNo: "",
            };
        },
        created() {

        },
        methods: {

            getTaxNo() {
                let that = this;
                let customList = that.dict.type.goods_customer;
                let currentCustomerId = that.form.customerId;
                customList.forEach((item) => {
                    if (currentCustomerId == item.value) {
                        that.taxNo = item.raw.remark;
                    }
                })
            },
            updateTotlePrice() {
                let that = this;
                if (that.form.amountReal && that.form.amount) {
                    let totlePrice = this.functionNumberMul(that.form.amountReal, that.form.amount);
                    that.$set(that.form, "remaining", totlePrice);
                }
            },
            functionNumberMul(arg1, arg2) {
                var m = 0;
                var s1 = arg1.toString();
                var s2 = arg2.toString();
                try {
                    m += s1.split(".")[1].length;
                } catch (e) {
                }
                try {
                    m += s2.split(".")[1].length;
                } catch (e) {
                }
                return Number((s1.replace(".", "")) - Number(s2.replace(".", ""))) / Math.pow(10, m);
            },
            selectCustomer(value) {
                let that = this;
                that.$nextTick(() => {
                    let arr = that.$refs.myselectCustomer;
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].currentValue == value) {
                            that.form.customerName = arr[i].label;
                        }
                    }
                })
            },
            selectSupplier(value) {
                let that = this;
                that.$nextTick(() => {
                    let arr = that.$refs.myselectSsupplier;
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].currentValue == value) {
                            that.form.supplierName = arr[i].label;
                        }
                    }
                })
            },
            selectUser(value) {
                let that = this;
                that.$nextTick(() => {
                    let arr = that.$refs.myselectUser;
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].currentValue == value) {
                            that.form.saleName = arr[i].label;
                        }
                    }
                })
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    no: null,
                    amount: null,
                    amountReal: null,
                    remaining: null,
                    customerId: null,
                    customerName: null,
                    taxNo: null,
                    invoiceDate: null,
                    invoiceCompany: null,
                    fundCallback: null,
                    backDate: null,
                    drawerId: null,
                    drawerName: null,
                    saleId: this.$store.getters.userId,
                    saleName: this.$store.getters.nickName,
                    files: null,
                    status: "0",
                    delFlag: null,
                    createBy: null,
                    createTime: null,
                    updateBy: null,
                    updateTime: null,
                    remark: null,
                };
                this.columns = [];
                this.showEditBtn = true;
                this.resetForm("form");
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加发票管理";
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                let that = this;
                that.reset();
                that.showEditBtn = false;
                const id = row.id || that.ids;
                getById(that.url.getById, id).then(response => {
                    that.form = response.data;
                    that.open = true;
                    that.title = "发票管理";
                    getById(that.url.listBatch, response.data.saleId).then(response => {
                        that.columns = response.rows;
                        that.total = response.total;
                        that.loading = false;
                    });
                    that.$nextTick(() => {
                        that.getTaxNo();
                    })
                });
                that.getList();
            },
            /** 财务修改发票号功能 */
            handleUpdateForCW(row) {
                let that = this;
                that.reset();
                that.showEditBtn = true;
                const id = row.id || that.ids;
                getById(that.url.getById, id).then(response => {
                    that.form = response.data;
                    that.open = true;
                    that.title = "发票管理";
                    getById(that.url.listBatch, response.data.saleId).then(response => {
                        that.columns = response.rows;
                        that.total = response.total;
                        that.loading = false;
                    });
                    that.$nextTick(() => {
                        that.getTaxNo();
                    })
                });
                // that.getList();
            },

            getList() {
                this.queryParams.invoiceId = this.invoiceId;
                getAction(this.url.list, this.queryParams).then(response => {
                    this.dataList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.id != null) {
                            updateAction(this.url.edit, this.form).then(response => {
                                this.$modal.msgSuccess("修改成功");
                                this.open = false;
                                this.$emit('ok');
                            });
                            /*updateInvoice(this.form).then(response => {
                                this.$modal.msgSuccess("修改成功");
                                this.open = false;
                                this.$emit('ok');
                            });*/
                        } else {
                            addAction(this.url.add, this.form).then(response => {
                                this.$modal.msgSuccess("新增成功");
                                this.open = false;
                                this.$emit('ok');
                            });
                        }
                    }
                });
            },
        }
    };
</script>
